package com.yunche.yunchebusiness

import android.content.Context
import android.view.View
import com.orhanobut.logger.Logger
import com.yunche.yunchebusiness.base.rx.BaseObserver
import com.yunche.yunchebusiness.utils.RegexUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jetbrains.anko.windowManager

/**
 * Create by Crcker on 2018/10/16 14:20
 * Email: Crcker@163.com
 * kotlin 扩展类
 */


//RX observer的扩展
fun <T> Observable<T>.execute(observer: BaseObserver<T>) {
    this.observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(observer)
}

fun String.toJson(): String {
    return ""
}

fun String.isIdCard(): Boolean {
    return RegexUtils.checkIdCard(this)
}

fun String.toRequestBody(): RequestBody {
    return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), this)
}

//拿到屏幕的宽度
fun Context.screenWidth(): Int {
    return windowManager.defaultDisplay.width
}

//拿到屏幕的高度
fun Context.screenHeight(): Int {
    return windowManager.defaultDisplay.height
}

fun String.getSameStr(str: String): Int {
    var i = 0
    for (s in split("")) {
        if (s == str) {
            i++
        }
    }
    return i
}

fun String.hasSame(str: String): Boolean {
    for (s in split("")) {
        Logger.t("xxx").d(s)
        if (s == str) {
            return true
        }
    }
    return false
}


//屏幕比例 16:9 18:9 19:9
fun Context.screenScale(): Float {
    var w = windowManager.defaultDisplay.width
    var h = windowManager.defaultDisplay.height
    return h.toFloat() / w.toFloat()
}

fun String.isPhone(): Boolean {
    return length == 11 && startsWith("1")
}


fun View.dip2px(dipValue: Float): Int {
    val scale = this.resources.displayMetrics.density
    return (dipValue * scale + 0.5f).toInt()
}

fun View.px2dip(pxValue: Float): Int {
    val scale = this.resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

fun durationFormat(duration: Long?): String {
    val minute = duration!! / 60
    val second = duration % 60
    return if (minute <= 9) {
        if (second <= 9) {
            "0$minute' 0$second''"
        } else {
            "0$minute' $second''"
        }
    } else {
        if (second <= 9) {
            "$minute' 0$second''"
        } else {
            "$minute' $second''"
        }
    }
}

/**
 * 数据流量格式化
 */
fun Context.dataFormat(total: Long): String {
    var result: String
    var speedReal: Int = (total / (1024)).toInt()
    result = if (speedReal < 512) {
        speedReal.toString() + " KB"
    } else {
        val mSpeed = speedReal / 1024.0
        (Math.round(mSpeed * 100) / 100.0).toString() + " MB"
    }
    return result
}